package org.dromara.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.dromara.app.appParams.AppDetailByIdParams;
import org.dromara.app.appParams.AppPageParams;
import org.dromara.app.appParams.AppPingLunpageParams;
import org.dromara.app.appParams.AppPublicUpdatesParams;
import org.dromara.app.appReturn.AppTrendsReturn;
import org.dromara.app.appReturn.AppYueJuPingLunReturn;
import org.dromara.app.cssUtils.CssUtils;
import org.dromara.app.domain.SkAppUser;
import org.dromara.app.domain.SkDongtaiPinglun;
import org.dromara.app.domain.SkFansUser;
import org.dromara.app.mapper.SkAppUserMapper;
import org.dromara.app.mapper.SkDongtaiPinglunMapper;
import org.dromara.app.mapper.SkFansUserMapper;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.dromara.app.domain.bo.SkUserTrendsBo;
import org.dromara.app.domain.vo.SkUserTrendsVo;
import org.dromara.app.domain.SkUserTrends;
import org.dromara.app.mapper.SkUserTrendsMapper;
import org.dromara.app.service.ISkUserTrendsService;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 用户发布动态Service业务层处理
 *
 * @author Evacuation
 * @date 2024-08-07
 */
@RequiredArgsConstructor
@Service
public class SkUserTrendsServiceImpl implements ISkUserTrendsService {

    private final SkUserTrendsMapper baseMapper;

    private final SkAppUserMapper skAppUserMapper;

    private final SkFansUserMapper skFansUserMapper;

    private final SkDongtaiPinglunMapper skDongtaiPinglunMapper;

    /**
     * 查询用户发布动态
     *
     * @param id 主键
     * @return 用户发布动态
     */
    @Override
    public SkUserTrendsVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询用户发布动态列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户发布动态分页列表
     */
    @Override
    public TableDataInfo<SkUserTrendsVo> queryPageList(SkUserTrendsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SkUserTrends> lqw = buildQueryWrapper(bo);
        Page<SkUserTrendsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户发布动态列表
     *
     * @param bo 查询条件
     * @return 用户发布动态列表
     */
    @Override
    public List<SkUserTrendsVo> queryList(SkUserTrendsBo bo) {
        LambdaQueryWrapper<SkUserTrends> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SkUserTrends> buildQueryWrapper(SkUserTrendsBo bo) {
        Map<String, Object> params = bo.getParams();
        //判断是否城市代理账户
        LoginUser user = LoginHelper.getLoginUser();
        if (user.getRolePermission().contains("cityAgent")) {
            //是城市代理人
            bo.setCity(user.getCity());
        }
        LambdaQueryWrapper<SkUserTrends> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), SkUserTrends::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getImage()), SkUserTrends::getImage, bo.getImage());
        lqw.eq(StringUtils.isNotBlank(bo.getCity()), SkUserTrends::getCity, bo.getCity());
        lqw.eq(StringUtils.isNotBlank(bo.getLongitude()), SkUserTrends::getLongitude, bo.getLongitude());
        lqw.eq(StringUtils.isNotBlank(bo.getLatitude()), SkUserTrends::getLatitude, bo.getLatitude());
        lqw.eq(bo.getUserId() != null, SkUserTrends::getUserId, bo.getUserId());
        lqw.orderByDesc(SkUserTrends::getCreateTime);
        return lqw;
    }

    /**
     * 新增用户发布动态
     *
     * @param bo 用户发布动态
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SkUserTrendsBo bo) {
        SkUserTrends add = MapstructUtils.convert(bo, SkUserTrends.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户发布动态
     *
     * @param bo 用户发布动态
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SkUserTrendsBo bo) {
        SkUserTrends update = MapstructUtils.convert(bo, SkUserTrends.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SkUserTrends entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除用户发布动态信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 动态列表
     *
     * @param params
     * @param req
     * @return
     */
    @Override
    public List<AppTrendsReturn> getTrendsList(AppPageParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        List<AppTrendsReturn> list = baseMapper.getTrendsList(params, CssUtils.getUserId(req));
        if (list.size() > 0) {
            for (AppTrendsReturn app : list) {
                if (app.getBirthday() != null && !app.getBirthday().equals("")) {
                    if (isValidYearMonth(app.getBirthday())) {
                        LocalDate bir = LocalDate.parse(app.getBirthday() + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        Period age = Period.between(bir, LocalDate.now());
                        if (age.getYears() < 0) {
                            app.setAge("0");
                        } else {
                            app.setAge(age.getYears() + "");
                        }

                    } else {
                        app.setAge("0");
                    }
                }
                //是否喜欢判断
                if (app.getIsLike() != null) {
                    app.setIsLike(1L);
                } else {
                    app.setIsLike(0L);
                }
                //评论列表
                List<SkDongtaiPinglun> listPingLun = skDongtaiPinglunMapper.selectList(
                    new QueryWrapper<SkDongtaiPinglun>().lambda()
                        .eq(SkDongtaiPinglun::getDongtaiId, app.getId())
                        .orderByDesc(SkDongtaiPinglun::getCreateTime)
                );
                List<AppYueJuPingLunReturn> all = BeanUtil.copyToList(listPingLun, AppYueJuPingLunReturn.class);
                app.setList(all);
                //判断是否点赞动态
                if (app.getLikeUserIds() != null && !app.getLikeUserIds().equals("")) {
                    String[] array = app.getLikeUserIds().split(",");
                    boolean contains = Arrays.asList(array).contains(CssUtils.getUserId(req) + "");
                    if (contains) {
                        app.setIsUserLike(1L);
                    } else {
                        app.setIsUserLike(0L);
                    }
                } else {
                    app.setIsUserLike(0L);
                }
                //判断是否是自己
                if (app.getUserId().longValue() == userId.longValue()) {
                    app.setIsMi(1L);
                } else {
                    app.setIsMi(0L);
                }
            }
        }
        return list;
    }

    /**
     * 时间判断
     */
    public static boolean isValidYearMonth(String text) {
        // 定义年月的正则表达式
        String regex = "^\\d{4}-\\d{2}$";
        // 检查文本是否匹配正则表达式
        if (text.matches(regex)) {
            try {
                // 使用DateTimeFormatter解析字符串
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
                formatter.parse(text);
                System.out.println("true");
                // 如果没有异常抛出，说明是有效的年月格式
                return true;
            } catch (Exception e) {
                // 字符串不是有效的日期
                System.out.println("false");
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 发布动态
     *
     * @param params
     * @param req
     */
    @Override
    public void publishUpdates(AppPublicUpdatesParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        SkUserTrends skUserTrends = BeanUtil.copyProperties(params, SkUserTrends.class);
        skUserTrends.setUserId(userId);
        skUserTrends.setCommonNum(0);
        skUserTrends.setLikeNum(0);
        baseMapper.insert(skUserTrends);
    }

    /**
     * 动态详情
     *
     * @param params
     * @param req
     * @return
     */
    @Override
    public AppTrendsReturn getTrendsInfo(AppDetailByIdParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        SkUserTrends skUserTrends = baseMapper.selectById(params.getId());
        AppTrendsReturn app = BeanUtil.copyProperties(skUserTrends, AppTrendsReturn.class);
        app.setIsLike(0L);
        if (skUserTrends.getLikeUserIds() != null && skUserTrends.getLikeUserIds().length() > 0) {
            String[] list = skUserTrends.getLikeUserIds().split(",");
            for (int i = 0; i < list.length; i++) {
                if (list[i].equals(userId + "")) {
                    app.setIsLike(1L);
                    break;
                }
            }
        }
        //发布人基本信息
        SkAppUser skAppUser = skAppUserMapper.selectById(skUserTrends.getUserId());
        app.setHeadImage(skAppUser.getHeadImage());
        app.setBirthday(skAppUser.getBirthday());
        app.setNickName(skAppUser.getNickName());
        app.setSex(skAppUser.getSex());
        //是否关注
        if (skAppUser.getId().longValue() == userId.longValue()) {
            app.setIsMi(1L);
        } else {
            app.setIsMi(0L);
            SkFansUser skFansUser = skFansUserMapper.selectOne(
                new QueryWrapper<SkFansUser>().lambda()
                    .eq(SkFansUser::getGzUserId, skAppUser.getId())
                    .eq(SkFansUser::getUserId, userId)
                    .last("limit 1")
            );
            if (skFansUser != null) {
                app.setIsUserLike(1L);
            } else {
                app.setIsUserLike(0L);
            }
        }
        return app;
    }

    @Override
    public List<AppTrendsReturn> getMyDongTaiList(AppPingLunpageParams params, HttpServletRequest req) {
        Long pageNumber = (params.getPageNum() - 1) * params.getPageSize();
        List<SkUserTrends> list = baseMapper.selectList(
            new QueryWrapper<SkUserTrends>().lambda()
                .eq(SkUserTrends::getUserId, params.getId())
                .orderByDesc(SkUserTrends::getCreateTime)
                .last("limit " + pageNumber + "," + params.getPageSize())
        );
        List<AppTrendsReturn> listAll = BeanUtil.copyToList(list, AppTrendsReturn.class);
        return listAll;
    }
}
